package com.ys.day27.p4线程池与并发;

import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.concurrent.*;

/**
 * 描述: P4Callable下载网络资源并返回结果
 *
 *
 * @author CodeYang
 * @version 2021/1/6 21:34
 */
public class P4Callable下载网络资源并返回结果 {


    public static void main(String[] args) throws ExecutionException {




        ExecutorService pool = Executors.newFixedThreadPool(5);

        for (int i = 0; i < FormNetWork.URL_PATH.length; i++) {
            Future<Boolean> future = pool.submit(new FormNetWork(i));
            try {
                System.out.println("下载:"+future.get());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        pool.shutdown();
    }




}

/**
 *  下载网络资源类
 */
class FormNetWork implements Callable<Boolean>{
    /**
     * 下载的资源
     */
    public final static String [] URL_PATH= {
            "http://n.sinaimg.cn/sports/2_img/upload/69e00db4/20170328/w1so-fycstxp52712761.jpg",
            "http://n.sinaimg.cn/sports/2_img/upload/69e00db4/20170328/k3tH-fyctevp9037944.jpg",
            "http://n.sinaimg.cn/sports/2_img/upload/69e00db4/20170328/a27s-fycstxp5271274.jpg",
            "http://n.sinaimg.cn/sports/2_img/upload/69e00db4/20170328/8IYH-fycstww1654561.jpg",
            "http://n.sinaimg.cn/sports/2_img/upload/69e00db4/20170328/ghEs-fycstww1654563.jpg"
    };

    private int index;

    /**
     *  通过控制 size来进行 URL的index 控制
     * @param size
     */
    public FormNetWork(int index) {
        this.index = index;
    }

    public FormNetWork() {
    }


    /**
     * 判断下载是否成功  加入线程池默认会执行该方法
     * @return
     * @throws Exception
     */
    @Override
    public Boolean call() throws Exception {
        try {
        // 下载资源到内存
        byte[] data = fromNetworkDownResource(URL_PATH[index]);
        String path = subNetTypeAddress(URL_PATH[index]);

            saveToDisk(data,path);
        } catch (Exception e) {
            System.out.println("写入失败");
            e.printStackTrace();
            return false;


        }
        return true;
    }

    /**
     *  将byte 数据写入磁盘
     * @param data
     * @param path
     * @throws Exception
     */
    private void saveToDisk(byte[] data, String path) throws  Exception{
        try (
                FileOutputStream fos = new FileOutputStream(path);
                ){
            fos.write(data);
            fos.flush();
        }
    }


    /**
     *
     从网络下载资源到内存
     *
     * @return 网络资源对应的字节数组
     * @throws Exception
     */
    private byte[] fromNetworkDownResource(String url) throws  Exception{
        URL urls = new URL(url);
        try(
                InputStream is = urls.openStream();
                ByteArrayOutputStream  bos = new ByteArrayOutputStream();
             )
         {
             // 把打开的网络资源写入内存流返回成功byte
             int len = 0;
             byte[] data = new byte[1024];
             while ((len = is.read(data))!=-1){
                 bos.write(data,0,len);
             }
             bos.flush();
             return  bos.toByteArray();
        }

    }

    /**
     *
     * @param url 对应的URL
     * @return 返回一个从网络下载下来对应的地址 拼接后 prefix + stuffix
     */
    private String subNetTypeAddress(String url){
        int index = url.lastIndexOf(".");
        //后缀资源
        String stuffix = url.substring(index);
        //前缀 系统时间
        long prefix = System.currentTimeMillis();
        StringBuffer str = new StringBuffer();
       return str.append("day_27/").append(prefix).append(stuffix).toString();

    }
}
